using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("SubTree")]
	[Category("Nested")]
	[Description("SubTree Node can be assigned an entire Sub BehaviorTree. The prime node of that behaviour will be considered child node of this node and will return whatever it returns")]
	[Icon("BT")]
	public class BTSubTree : BTNodeBase, INestedNode
	{
		[SerializeField]
		private BehaviourTree _nestedTree;

		private bool instantiated;

		private BehaviourTree nestedTree
		{
			get
			{
				return _nestedTree;
			}
			set
			{
				_nestedTree = value;
				if (_nestedTree != null)
				{
					_nestedTree.agent = base.graphAgent;
					_nestedTree.blackboard = base.graphBlackboard;
				}
			}
		}

		public Graph nestedGraph
		{
			get
			{
				return nestedTree;
			}
			set
			{
				nestedTree = (BehaviourTree)value;
			}
		}

		public override string nodeName
		{
			get
			{
				return base.nodeName.ToUpper();
			}
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			CheckInstance();
			if ((bool)nestedTree && (bool)nestedTree.primeNode)
			{
				return nestedTree.primeNode.Execute(agent, blackboard);
			}
			return Status.Success;
		}

		protected override void OnReset()
		{
			if ((bool)nestedTree && (bool)nestedTree.primeNode)
			{
				nestedTree.primeNode.ResetNode();
			}
		}

		public override void OnGraphStarted()
		{
			if (!nestedTree)
			{
				return;
			}
			CheckInstance();
			foreach (Node allNode in nestedTree.allNodes)
			{
				allNode.OnGraphStarted();
			}
		}

		public override void OnGraphStoped()
		{
			if (!nestedTree)
			{
				return;
			}
			foreach (Node allNode in nestedTree.allNodes)
			{
				allNode.OnGraphStoped();
			}
		}

		public override void OnGraphPaused()
		{
			if (!nestedTree)
			{
				return;
			}
			foreach (Node allNode in nestedTree.allNodes)
			{
				allNode.OnGraphPaused();
			}
		}

		private void CheckInstance()
		{
			if (!instantiated && nestedTree != null && nestedTree.transform.parent != base.graph.transform)
			{
				nestedTree = Object.Instantiate(nestedTree, base.transform.position, base.transform.rotation);
				nestedTree.transform.parent = base.graph.transform;
				instantiated = true;
			}
		}
	}
}
